<script>

import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import dayjs from 'dayjs'
import store from '@/store'

export default {
  name: 'ProductQualityStatusForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      disableSubmit: false,
      model: {
        productionDate: dayjs().format('YYYY-MM-DD'),
      },
      validatorRules: {
        planNumber: [
          { required: true, message: '请输入计划单号!' }
        ]
      },
      refKeys: ['productQualityStatusItem', 'productQualityStatusCheckResult'],
      tableKeys: ['productQualityStatusItem', 'productQualityStatusCheckResult'],
      activeKey: 'productQualityStatusItem',
      // 成品质量状态单明细表
      productQualityStatusItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '品牌',
            key: 'brand',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '成品代码',
            key: 'finishedProductCode',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.normal
          },
          {
            title: '数量',
            key: 'quantity',
            type: JVXETypes.normal,
            width: '150px',
          },
          {
            title: '订单编号',
            key: 'orderNumber',
            type: JVXETypes.normal,
            width: '150px',
          },
          {
            title: '订单完成',
            key: 'orderCompletion',
            type: JVXETypes.normal,
            width: '100px'
          }
        ]
      },
      // 成品质量状态检查项结果表
      productQualityStatusCheckResultTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '部门',
            key: 'qualityProcessName',
            type: JVXETypes.normal,
            width: '130px'
          },
          {
            title: '检查指引',
            key: 'checkGuide',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '成功标准',
            key: 'successStandard',
            type: JVXETypes.normal
          },
          {
            title: '结果',
            key: 'result',
            type: JVXETypes.slot,
            width: '100px',
            align: 'center',
            slotName: 'result'
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.slot,
            width: '150px',
            slotName: 'remark'
          },
          {
            title: '检查人',
            key: 'checkBy',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '确认时间',
            key: 'confirmTime',
            type: JVXETypes.normal,
            width: '100px'
          }
        ]
      },
      url: {
        add: '/qms/inspection/plan/product-quality/status/add',
        edit: '/qms/inspection/plan/product-quality/status/edit',
        queryById: '/qms/inspection/plan/product-quality/status/queryById',
        productQualityStatusItem: {
          list: '/qms/inspection/plan/product-quality/status/queryProductQualityStatusItemByMainId'
        },
        productQualityStatusCheckResult: {
          list: '/qms/inspection/plan/product-quality/status/queryProductQualityStatusCheckResultByMainId'
        },
        productQualityStatusCheck: {
          list: '/qms/inspection/plan/product-quality/check/listAll'
        },
        workshopPlanInfo: {
          list: '/wms/inbound/work-inbound-record/listWorkPlans'
        }
      },
      workshopPlanId: null,
      userInfo: store.getters.userInfo
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  methods: {
    confirm(record) {
      this.model.planNumber = record.code
      this.workshopPlanId = record.id
      this.confirmBefore()
      if (record.qualityStatusId) {
        this.model.id = record.qualityStatusId
        this.editAfter()
        this.visible = true
        return
      }
      this.fetchQualityStatusCheckItemData()
      this.visible = true
    },
    confirmBefore() {
      this.productQualityStatusItemTable.dataSource = []
      this.productQualityStatusCheckResultTable.dataSource = []
    },
    fetchQualityStatusCheckItemData() {
      this.requestSubTableData(this.url.productQualityStatusCheck.list, {}, this.productQualityStatusCheckResultTable, () => {
        if (this.productQualityStatusCheckResultTable.dataSource && this.productQualityStatusCheckResultTable.dataSource.length > 0) {
          this.productQualityStatusCheckResultTable.dataSource.forEach(item => {
            this.$set(item, 'createBy', null)
            this.$set(item, 'createTime', null)
          })
        }
      })
      this.fetchWorkshopPlanInfo()
    },
    fetchWorkshopPlanInfo() {
      if (!this.workshopPlanId) {
        return
      }
      getAction(this.url.workshopPlanInfo.list, { workshopPlanId: this.workshopPlanId }).then(res => {
        let { result } = res
        if (result) {
          this.productQualityStatusItemTable.dataSource = result.map(item => {
            return {
              ...item,
              orderNumber: item.orderNo,
              finishedProductCode: item.materialCode,
              quantity: item.planQuantity,
              brand: item.salesType_dictText,
              orderCompletion: item.storedQuantity >= item.planQuantity ? 'Y' : 'N'
            }
          })
        }
      })
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        getAction(this.url.queryById, { id: this.model.id }).then(res => {
          const { result } = res
          if (result) {
            this.model = result
          }
        })
        this.requestSubTableData(this.url.productQualityStatusItem.list, params, this.productQualityStatusItemTable)
        this.requestSubTableData(this.url.productQualityStatusCheckResult.list, params, this.productQualityStatusCheckResultTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        productQualityStatusItemList: allValues.tablesValue[0].tableData,
        productQualityStatusCheckResultList: allValues.tablesValue[1].tableData
          .filter(item => item.result).map(item => {
            return {
              id: item.resultId,
              planNumber: this.model.planNumber,
              qualityProcess: item.qualityProcess,
              result: item.result,
              remark: item.remark
            }
          })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    rowspanMethod({ row, column, rowIndex, columnIndex }) {
      const visibleData = this.productQualityStatusCheckResultTable.dataSource
      const cellValue = row[column.property]
      if (column.property === 'qualityProcessName' && cellValue) {
        const prevRow = visibleData[rowIndex - 1]
        let nextRow = visibleData[rowIndex + 1]
        if (prevRow && prevRow['qualityProcessName'] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow['qualityProcessName'] === cellValue) {
            nextRow = visibleData[++countRowspan + rowIndex]
          }
          return { rowspan: countRowspan, colspan: 1 }
        }
      }
      const fieldName = 'qualityProcess'
      if (['result', 'checkBy', 'confirmTime', 'remark'].includes(column.property)) {
        const prevRow = visibleData[rowIndex - 1]
        let nextRow = visibleData[rowIndex + 1]
        if (prevRow && prevRow[fieldName] === row[fieldName]) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[fieldName] === row[fieldName]) {
            nextRow = visibleData[++countRowspan + rowIndex]
          }
          return { rowspan: countRowspan, colspan: 1 }
        }
      }
    }
  }
}
</script>

<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="状态单号" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="qualityStatusNumber">
              <a-input v-model="model.qualityStatusNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productionDate">
              <j-date placeholder="请选择生产日期" v-model="model.productionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="生产工厂" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productionFactory">
              <a-input v-model="model.productionFactory" placeholder="请输入生产工厂"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <div style="margin: 10px 0">
              <j-vxe-table
                keep-source
                :ref="refKeys[0]"
                :loading="productQualityStatusItemTable.loading"
                :columns="productQualityStatusItemTable.columns"
                :dataSource="productQualityStatusItemTable.dataSource"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="false"
                :toolbar="false"
              />
            </div>
            <div style="margin: 10px 0">
              <j-vxe-table
                keep-source
                :ref="refKeys[1]"
                :loading="productQualityStatusCheckResultTable.loading"
                :columns="productQualityStatusCheckResultTable.columns"
                :dataSource="productQualityStatusCheckResultTable.dataSource"
                :maxHeight="500"
                :disabled="formDisabled"
                :rowNumber="false"
                :rowSelection="false"
                :toolbar="false"
                :span-method="rowspanMethod"
              >
                <template v-slot:result="{ row }">
                  <a-select
                    v-if="!row.checkBy || row.checkBy===userInfo.username"
                    v-model="row.result">
                    <a-select-option value="Y">Y</a-select-option>
                    <a-select-option value="N">N</a-select-option>
                  </a-select>
                  <span v-else>{{ row.result }}</span>
                </template>
                <template v-slot:remark="{ row }">
                  <j-input-pop
                    v-if="!row.checkBy || row.checkBy===userInfo.username"
                    :width="300"
                    :height="210"
                    v-model="row.remark"
                    style="width: 100%;"
                  />
                  <span v-else>{{ row.remark }}</span>
                </template>
              </j-vxe-table>
            </div>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品放行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productRelease">
              <a-input v-model="model.productRelease" placeholder="请输入产品放行"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品放行人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="releaseStaff">
              <a-input v-model="model.releaseStaff" placeholder="请输入产品放行人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="放行日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="releaseDate">
              <j-date placeholder="请选择放行日期" v-model="model.releaseDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品扣押" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productHold">
              <a-input v-model="model.productHold" placeholder="请输入产品扣押"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="扣押原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="holdReason">
              <a-input v-model="model.holdReason" rows="4" placeholder="请输入扣押原因" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="扣押产品处理" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="holdProcessing">
              <a-input v-model="model.holdProcessing" rows="4" placeholder="请输入扣押产品处理" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="扣押日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="holdQaDate">
              <j-date placeholder="请选择扣押日期" v-model="model.holdQaDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="工厂QA" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="factoryQa">
              <a-input v-model="model.factoryQa" placeholder="请输入工厂QA"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="批准QA" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalQa">
              <a-input v-model="model.approvalQa" placeholder="请输入批准QA"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="批准日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalDate">
              <j-date placeholder="请选择批准日期" v-model="model.approvalDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<style scoped>

</style>